<template>
    <div class="achievement-list-page">
        <el-card shadow="never" class="mt-4">
            <el-form :inline="true" @keyup.enter.native="onSubmit">
                <el-form-item label="企业" v-if="!isCompanyAccount()">
                    <el-select
                        v-model="form.companyId"
                        clearable
                        @change="onSubmit()">
                        <el-option
                            v-for="item in companyOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="团队" v-if="isCompanyAccount()">
                    <el-select
                        v-model="form.teamId"
                        clearable
                        @change="onSubmit()">
                        <el-option
                            v-for="item in teamOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="职位">
                    <el-select
                        v-model="form.positionId"
                        clearable
                        @change="fetchData()">
                        <el-option
                            v-for="item in positionOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="关键词" prop="keyword">
                    <el-input
                    v-model="form.keyword"
                    placeholder="员工姓名与邮箱搜索"
                    class="input-width"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input
                        v-model="form.phone"
                        placeholder="请输入手机号"
                        class="input-width"></el-input>
                </el-form-item>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
                <el-button type="primary" @click="resetForm">重置</el-button>
            </el-form>
            <div v-if="isCompanyAccount() && accountInfo" class="flex">
                <div>您共拥有 {{accountInfo.count}} 个员工账号配额权益,</div>
                <div class="ml-3">未使用 {{accountInfo.active_count}} 个</div>
            </div>

            <div v-if="isCompanyAccount() && accountInfo" class="flex mt-4">
                <div>您共拥有 {{ medalCdkeyData.total_num }} 个勋章课兑换码,</div>
                <div class="ml-3">
                    未使用 {{ medalCdkeyData.not_used_num}} 个
                </div>
            </div>

            <div class="mt-5">
                <el-button
                type="primary"
                @click="onAddClick" v-if="isCompanyAccount()">配置员工学习账号</el-button>
                <el-button
                    :loading="loading"
                    type="primary"
                    @click="importStaffInpClick" v-if="isCompanyAccount()">导入员工信息</el-button>
                <el-button
                    @click="onExportStaff"
                    type="primary"
                    v-if="isCompanyAccount()">导出员工信息</el-button>
                <el-button type="primary" @click="medalUserVisible = true">勋章课兑换码配额情况</el-button>
                <el-button type="primary" @click="medalExchangeVisible = true">勋章课兑换码已兑换列表</el-button>
                <a :href="onExportStaffTemp()" target="_blank" class="text-sm ml-2 border-b">下载员工信息模板</a>
            </div>
            <input @change="getUserFile" type="file" accept=".xls,.xlsx" ref="importStaff" style="display: none;">

            <div class="mt-3" v-loading="loading">
                <el-table :data="data">
                    <el-table-column type="index"
                    :index="indexMethod"
                    align="center"
                    label="序号"
                    width="50"/>
                    <el-table-column label="姓名" prop="name" width="70"></el-table-column>
                    <el-table-column label="手机号" prop="phone"></el-table-column>
                    <el-table-column label="邮箱" prop="email"></el-table-column>
                    <el-table-column label="职位" prop="position"></el-table-column>
                    <el-table-column label="团队" prop="team" v-if="!isCompanyAccount()"></el-table-column>
                    <el-table-column label="密码" v-if="isCompanyAccount()">
                        <template slot-scope="{row}">
                            {{ showPlainPwd(row.plain_psw) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="已使用天数">
                        <template slot-scope="{row}">
                            {{ row.active_time | usedDay(row.expiry_time, dateTimestamp, row.active_day) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="剩余天数">
                        <template slot-scope="{row}">
                            {{ row.expiry_time | restDayFilter(tomorrowDateTimestamp) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="企业" prop="company" v-if="!isCompanyAccount()"/>
                    <el-table-column label="最后登录" v-if="isCompanyAccount()">
                        <template slot-scope="{row}">
                            {{ formatTime(row.last_login_at) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="注册时间">
                        <template slot-scope="{row}">
                            {{ formatTime(row.created_at, 'YYYY-MM-DD') }}
                        </template>
                    </el-table-column>
                    <el-table-column width="150" align="center" label="操作">
                        <template slot-scope="{row}">
                            <el-button
                                v-if="isCompanyAccount()"
                                type="text"
                                @click="onMedalDialog(row)">分配勋章课兑换码</el-button>
                            <el-button
                                v-if="!$store.state.my.company_id"
                                type="text"
                                @click="getUserData(row)">编辑</el-button>
                            <el-button
                                v-if="isCompanyAccount()"
                                type="text"
                                @click="onEditClick(row)">编辑</el-button>
                            <el-button
                                v-if="isCompanyAccount()"
                                type="text"
                                @click="onAccountClick(row)">账号配额</el-button>
                            <el-button
                                v-if="!isCompanyAccount()"
                                type="text"
                                @click="getUserDetail(row)">查看用户邀请</el-button>
                            <el-button
                                type="text"
                                class="red-color"
                                @click="onRestClick(row)">重置密码</el-button>
                            <el-button
                                v-if="isCompanyAccount()"
                                :type="row.status === 1 ? 'primary' : 'success'"
                                @click="onStatusClick(row)">
                                    {{ row.status === 1 ? '冻结' : '恢复' }}</el-button>
                            <el-button
                                v-if="isCompanyAccount()"
                                type="text"
                                @click="onDeleteClick(row)"
                                class="red-color">删除</el-button>
                            <el-button
                                v-if="isCompanyAccount() && !row.email"
                                type="text"
                                @click="onBindEmail(row)">绑定邮箱</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-if="totalElements > 0" class="footer">
                <pagination
                ref="pagination"
                :currentPage="form.page"
                :pageSize="form.size"
                :handleCurrentChange="onCurrentChange"
                :handlePageSizeChange="onPageSizeChange"
                :totalElements="totalElements"
                ></pagination>
            </div>
        </el-card>
        <el-dialog
            title="用户邀请详情列表"
            :visible.sync="visible"
            width="60%"
            :modal-append-to-body="false"
        >
            <el-table :data="dialogData">
                <el-table-column align="center" label="账号" prop="email"/>
                <el-table-column align="center" label="员工头像">
                    <template slot-scope="{row}">
                        <img class="w-16 h-16" v-if="row.avatar" :src="row.avatar" alt="">
                    </template>
                </el-table-column>
                <el-table-column align="center" label="员工姓名" prop="name"/>
                <el-table-column align="center" label="手机号" prop="phone"/>
                <el-table-column align="center" label="邀请时间">
                    <template slot-scope="{row}">
                        {{ formatTime(row.created_at, 'YYYY-MM-DD') }}
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-center" v-if="dialogForm.total > 0">
                <el-pagination
                    @current-change="fetchInviteData"
                    :current-page.sync="dialogForm.page"
                    :page-size="dialogForm.size"
                    layout="total, prev, pager, next, jumper"
                    :total="dialogForm.total">
                </el-pagination>
            </div>
        </el-dialog>

        <el-dialog
            title="员工信息修改"
            :visible.sync="userVisible"
            width="60%"
            :modal-append-to-body="false">
            <el-form
                label-width="90px"
                label-position="right"
                @submit.native.prevent>
                <el-form-item label="姓名:" required>
                    <el-input class="input-width" v-model.trim="userForm.name" placeholder="请输入员工姓名"></el-input>
                </el-form-item>
                <el-form-item label="电话号码:">
                    <el-input class="input-width" v-model.trim="userForm.phone" placeholder="请输入电话号码"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="text-center">
                <el-button type="primary" @click="onChangeUser">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog
            title="导入员工信息（不正确信息会出现红框，请输入正确格式）"
            :visible.sync="importUserVisible"
            width="60%">
            <div class="flex">
                <el-select v-model="applicationId" class="w-full">
                    <el-option
                        v-for="item in applicationOptions"
                        :key="item.id"
                        :label="`共${item.count - item.used_count}个账号配额。每个可用${item.duration}天的账号配额`"
                        :value="item.id"/>
                </el-select>
                <el-button type="primary">已选人数：{{ selectUser.length }}</el-button>
            </div>
            <el-table height="500" :data="importUserList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"/>
                <el-table-column label="昵称" prop="name"/>
                <el-table-column label="电话号码">
                    <template slot-scope="{row}">
                        <el-input
                            :class="`${importUserVerify(row, 'phone')} border-red-400`"
                            v-model="row.phone"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="邮箱">
                    <template slot-scope="{row}">
                        <el-input
                            :class="`${importUserVerify(row, 'email')} border-red-400`"
                            v-model="row.email"></el-input>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="text-center">
                <el-button type="primary" @click="importUserAccount">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog
            title="勋章课兑换码列表"
            :visible.sync="medalCdkeyVisible"
            width="60%">
            <el-button :disabled="!selectCdkey.length" type="primary" @click="onAllotCdkey">确 定</el-button>
            <el-table
                ref="medalTable"
                :data="medalCdkeyList"
                @selection-change="medalHandleSelection"
                :row-key="(row) => row.id">
                <el-table-column
                    reserve-selection
                    :selectable="(row) => row.status === 1 || row.status === 3"
                    type="selection"
                    width="50"/>
                <el-table-column label="勋章课程兑换码名称" prop="code"/>
                <el-table-column label="兑换用户名" prop="user_name"/>
                <el-table-column label="兑换用户电话/邮箱" prop="contact_information"/>
                <el-table-column label="是否已兑换">
                    <template slot-scope="{row}">
                        {{ row.status === 2 ? '已兑换'
                            : row.status === 4 ? `已分配给用户：${row.assign_user_name}` : '未兑换' }}
                    </template>
                </el-table-column>
                <el-table-column label="兑换时间">
                    <template slot-scope="{row}">
                        {{ row.exchange_at | formatTime }}
                    </template>
                </el-table-column>
                <el-table-column label="创建时间">
                    <template slot-scope="{row}">
                        {{ row.created_at | formatTime }}
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="text-center">
                <el-pagination
                    @current-change="fetchMedalCdkey"
                    :current-page.sync="medalCdkeyForm.page"
                    :page-size.sync="medalCdkeyForm.size"
                    :total="medalCdkeyForm.total">
                </el-pagination>
            </div>
        </el-dialog>

        <el-dialog
            title="勋章课兑换码配额列表"
            :visible.sync="medalUserVisible"
            width="60%">
            <el-table :data="medalUserList">
                <el-table-column label="员工姓名" prop="name"/>
                <el-table-column label="未使用兑换码个数" prop="not_used_num"/>
                <el-table-column label="已使用兑换码个数" prop="used_num"/>
            </el-table>
        </el-dialog>

        <el-dialog
            title="勋章课兑换码已兑换列表"
            :visible.sync="medalExchangeVisible"
            width="60%">
            <el-table :data="medalExchangeList">
                <el-table-column label="兑换码" prop="code"/>
                <el-table-column label="兑换课程名字" prop="course"/>
                <el-table-column label="兑换用户名" prop="user_name"/>
                <el-table-column label="兑换时间">
                    <template slot-scope="{row}">
                        {{ row.exchange_at | formatTime }}
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="text-center">
                <el-pagination
                    @current-change="fetchMedalExchange"
                    :current-page.sync="medalExchangeForm.page"
                    :page-size.sync="medalExchangeForm.size"
                    :total="medalExchangeForm.total">
                </el-pagination>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import Pagination from '../../components/base/Pagination';
import TimeFormats from '../../helpers/TimeFormats';
import AesCrypt from '../../helpers/AesCrypt';
import IndexNumber from '../../helpers/IndexNumber';

export default {
    components: {
        Pagination,
    },
    mixins: [require('../../mixins/CacheQuery').default],
    data() {
        return {
            loading: false,
            userVisible: false,
            data: [],
            form: {
                page: 1,
                size: 50,
                keyword: '',
                teamId: '',
                companyId: '',
                positionId: '',
                phone: '',
            },
            accountInfo: '',
            totalElements: 0,
            teamOptions: [],
            companyOptions: [],
            positionOptions: [],
            // 当前日期零时零分时间戳
            dateTimestamp: '',
            // 明日日期零时零分时间戳
            tomorrowDateTimestamp: '',
            dialogData: [],
            dialogForm: {
                size: 10,
                page: 1,
                total: 0,
            },
            inviteId: 0,
            visible: false,
            userForm: {
                name: '',
                phone: '',
            },

            importUserList: [],
            importUserVisible: false,
            applicationId: '',
            selectUser: [],
            applicationOptions: [],

            medalCdkeyVisible: false,
            medalCdkeyForm: {
                page: 1,
                size: 10,
                total: 0,
                company_id: '',
            },
            medalCdkeyList: [],
            medalCdkeyUserId: '',
            selectCdkey: [],

            medalCdkeyData: '',
            medalUserVisible: false,
            medalUserList: [],

            medalExchangeVisible: false,
            medalExchangeForm: {
                page: 1,
                size: 10,
                total: 0,
            },
            medalExchangeList: [],
        };
    },
    filters: {
        usedDay: function (activeTime, expiryTime, dateTimestamp, activeDay) {
            if (activeTime > 0 && expiryTime > 0) {
                if (dateTimestamp >= expiryTime) {
                    // 已过期
                    return activeDay;
                }
                // 未过期下 总天数 = 累积已使用天数 + 与当天计算已使用天数
                return activeDay + ((dateTimestamp - activeTime) / 86400);
            }
            return '';
        },
        restDayFilter: function (expiryTime, tomorrowDateTimestamp) {
            if (expiryTime > 0) {
                if (tomorrowDateTimestamp < expiryTime) {
                    return (expiryTime - tomorrowDateTimestamp) / 86400;
                }
            }
            return 0;
        },
    },
    watch: {
        userVisible(val) {
            if (!val) {
                this.userForm = {
                    name: '',
                    phone: '',
                };
            }
        },
    },
    methods: {
        initDateTimestamp() {
            const now = new Date();
            // const today = now.toLocaleDateString().split('/').join('-');
            // safari获取时间出现获取不到,时间格式须为 2019/5/21 而不是 2019-5-21
            const date = new Date(now.toLocaleDateString());
            this.dateTimestamp = date.getTime() / 1000;
            this.tomorrowDateTimestamp = this.dateTimestamp + 86400;
        },
        showPlainPwd(plainPsw) {
            return plainPsw ? new AesCrypt().decryptCBC(plainPsw) : '';
        },
        formatTime(timestamp, format) {
            return timestamp ? new TimeFormats().convertTime(format, timestamp) : '';
        },
        isCompanyAccount() {
            return this.$store.state.my.company_id > 0;
        },
        onSubmit() {
            this.form.page = 1;
            this.fetchData();
        },
        onResetFilters() {
            this.$refs.form.resetFields();
        },
        onCurrentChange(val) {
            this.form.page = val;
            this.fetchData();
        },
        onPageSizeChange(val) {
            this.form.size = val;
            this.form.page = 1;
            this.fetchData();
        },
        fetchData() {
            this.loading = true;
            API.get('user', {params: this.form}).then((res) => {
                this.data = res.content;
                this.totalElements = res.pagination.total;
            }).finally(() => {
                this.loading = false;
            });
        },
        onEditClick({id}) {
            this.$router.push({
                name: 'UserManage.Add',
                params: { id: id },
            });
        },
        onAddClick() {
            this.$router.push({
                name: 'UserManage.Add',
            });
        },
        onDeleteClick({id}) {
            $ele.$confirm('是否删除此员工', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API.delete(`user/${id}`, {
                }).then(() => {
                    $ele.$message.success('删除成功');
                    this.fetchData();
                }).finally(() => {
                    this.loading = false;
                });
            }).catch(() => { });
        },
        fetchTeam() {
            API.get('role/list', {
                params: {
                    type: 3,
                },
            }).then((res) => {
                this.teamOptions = res;
            });
        },
        fetchPosition() {
            API.get('position/list').then((res) => {
                this.positionOptions = res;
            });
        },
        onRestClick({id}) {
            API.put(`user/reset/${id}`).then((res) => {
                $ele.$confirm(`重置密码成功，当前账号的登陆密码是${res.password}`, '提示', {
                    confirmButtonText: '确定',
                    type: 'warning',
                });
                this.fetchData();
            });
        },
        onStatusClick(row) {
            const content = row.status === 1 ? '是否冻结此员工账号' : '是否解除此员工账号冻结状态';
            const requestStatus = row.status === 1 ? 2 : 1;
            $ele.$confirm(content, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API.put(`user/${row.id}/${requestStatus}`).then(() => {
                    $ele.$message.success('操作成功');
                    this.fetchData();
                }).finally(() => {
                    this.loading = false;
                });
            }).catch(() => { });
        },
        onAccountClick({id}) {
            this.$router.push({
                name: 'UserManage.Account',
                params: { id: id },
            });
        },
        resetForm() {
            this.form.keyword = '';
            this.form.teamId = '';
            this.form.positionId = '';
            this.form.companyId = '';
            this.form.phone = '';
            this.onSubmit();
        },
        fetchAccountInfo() {
            API.get('company/account').then((res) => {
                this.accountInfo = res;
            });
        },
        fetchCompany() {
            API.get('company/list').then((res) => {
                this.companyOptions = res;
            });
        },
        getUserDetail(row) {
            this.loading = true;
            this.inviteId = row.id;
            this.dialogForm.page = 1;
            API.get(`user/invite/${row.id}`, {params: this.dialogForm})
                .then((res) => {
                    this.dialogData = res.content;
                    this.dialogForm.total = res.pagination.total;
                    this.onDialog();
                }).finally(() => this.loading = false);
        },
        fetchInviteData() {
            this.loading = true;
            API.get(`user/invite/${this.inviteId }`, {params: this.dialogForm})
                .then((res) => {
                    this.dialogData = res.content;
                    this.dialogForm.total = res.pagination.total;
                }).finally(() => this.loading = false);
        },
        onDialog() {
            this.visible = !this.visible;
        },
        indexMethod(index) {
            return new IndexNumber()
                .getIndex(this.totalElements, this.form.page, this.form.size, index);
        },

        onUserDialog() {
            this.userVisible = !this.userVisible;
        },
        getUserData({id}) {
            this.loading = true;
            API.get(`user/${id}`).then(res => {
                this.userForm = res;
                this.onUserDialog();
            }).finally(() => this.loading = false);
        },
        onChangeUser() {
            const form = this.userForm;
            if (!form.name) return $ele.$message.warning('请输入员工姓名');

            this.loading = true;
            API.put(`user/${form.id}`, form).then(() => {
                $ele.$message.success('修改成功');
                this.fetchData();
                this.onUserDialog();
            }).finally(() => this.loading = false);
        },

        // 5.1 version 对接企业微信登录
        // 绑定邮箱
        onBindEmail(row) {
            this.loading = true;
            API.get(`user/wx-email/${row.id}`).then(res => {
                if (res) {
                    this.onConfirmWx(res, row.id);
                } else {
                    $ele.$prompt('未获取到邮箱，请手动输入邮箱！', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }).then(({ value }) => {
                        this.onConfirmWx(value, row.id);
                    }).catch();
                }
            }).finally(() => this.loading = false);
        },
        onConfirmWx(email, id) {
            $ele.$confirm(`绑定邮箱：${email}，是否继续此操作？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API.post('user/blind-email', {
                    email, id,
                }).then(() => {
                    $ele.$message.success('绑定成功');
                    this.fetchData();
                }).finally(() => this.loading = false);
            }).catch(() => { });
        },
        // 5.1 end

        // 6.1导入逻辑
        // 6.1导入逻辑
        importStaffInpClick() {
            this.$refs.importStaff.click();
        },

        getUserFile(e) {
            const file = e.target.files[0];
            const formData = new FormData();
            formData.append('file', file);

            this.loading = true;
            API.post('user/import-user', formData).then((res) => {
                const list = res || [];

                let num = 1;
                this.importUserList = list.map(item => {
                    item.key = num;
                    num += 1;
                    return item;
                });
                this.importUserVisible = true;
            }).finally(() => {
                e.target.value = '';
                this.loading = false;
            });
        },

        handleSelectionChange(e) {
            this.selectUser = e || [];
        },

        importUserAccount() {
            const selectUser = this.selectUser;

            if (this.applicationId === '') return $ele.$message.warning('请选择账号配额');
            if (!selectUser.length) return $ele.$message.warning('请选择员工账号');

            let applicationIdNum = 0;
            for (const item of this.applicationOptions) {
                if (item.id === this.applicationId) applicationIdNum = item.count - item.used_count;
            }
            if (applicationIdNum < selectUser.length) return $ele.$message.warning('所选账号已超过当前账号配额');

            const map = new Map();
            for (const item of selectUser) {
                if (this.importUserVerify(item, 'phone')) return $ele.$message.warning('所选账号中，有账号的手机号格式不正确');
                if (this.importUserVerify(item, 'email')) return $ele.$message.warning('所选账号中，有账号的邮箱格式不正确');

                if (!map.has(item.phone)) {
                    map.set(item.phone, true);
                } else return $ele.$message.warning('所选账号有重复使用手机号数据');

                if (!map.has(item.email)) {
                    map.set(item.email, true);
                } else return $ele.$message.warning('所选账号有重复使用邮箱数据');
                map.set(item.key, true);
            }

            const form = {};
            form.application_id = this.applicationId;
            form.users = selectUser.map(item => {
                item.application_id = this.applicationId;
                return item;
            });
            API.post('user/batch-import-user', form).then(() => {
                $ele.$message.success('生成账号成功');
                this.importUserList = this.importUserList.filter(item => {
                    if (map.has(item.key)) return false;
                    return item;
                });
                this.fetchData();
            });
        },

        fetchApplicationData() {
            API.get('account/application/list').then((res) => {
                this.applicationOptions = res.filter(option => option.count > option.used_count);
            });
        },

        importUserVerify(row, type) {
            const email = /\S+@\S+\.\S+/;
            const phone = /^1[3456789]\d{9}$/;
            if (!email.test(row[type]) && type === 'email') return 'border';
            if (!phone.test(row[type]) && type === 'phone') return 'border';
            return '';
        },

        onExportStaff() {
            window.location.href = `${process.env.VUE_APP_API_PREFIX}user/export-user`;
        },

        onExportStaffTemp() {
            return `${process.env.VUE_APP_API_PREFIX}user/export-template`;
        },
        // 6.1导入逻辑
        // 6.1导入逻辑

        // 6.1勋章课兑换码
        // 6.1勋章课兑换码
        onMedalDialog(row) {
            this.medalCdkeyUserId = row.id;
            this.medalCdkeyVisible = true;
        },

        // 勋章课兑换码列表
        fetchMedalCdkey() {
            API.get('merit_exchange_code/page', {
                params: {
                    ...this.medalCdkeyForm,
                    company_id: this.$store.state.my.company_id,
                },
            }).then(res => {
                this.medalCdkeyList = res.content;
                this.medalCdkeyForm.total = res.pagination.total;
            });
        },

        onAllotCdkey() {
            if (!this.selectCdkey.length) return $ele.$message.warning('请选择员工');
            $ele.$confirm('是否将兑换码分配给此员工？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API.put('merit_exchange_code/user', {
                    ids: this.selectCdkey,
                    user_id: this.medalCdkeyUserId,
                }).then(() => {
                    this.fetchMedalCdkey();
                    this.selectCdkey = [];
                    $ele.$message.success('分配成功');
                    this.$refs.medalTable.clearSelection();
                }).finally(() => this.loading = false);
            }).catch();
        },

        medalHandleSelection(e) {
            const codeList = [];
            for (const item of e) {
                codeList.push(item.id);
            }
            this.selectCdkey = codeList;
        },

        // 公司兑换码数量
        getMedalCdkey() {
            API.get('merit_course/companys/quota').then(res => {
                this.medalCdkeyData = res;
            });
        },

        // 公司员工的兑换码信息
        getMedalUserCdkey() {
            API.get('merit_course/users').then(res => {
                this.medalUserList = res;
            });
        },

        fetchMedalExchange() {
            API.get('merit_course/companys/redeemed', {params: this.medalExchangeForm}).then((res) => {
                this.medalExchangeList = res.content;
                this.medalExchangeForm.total = res.pagination.total;
            }).finally(() => this.loading = false);
        },
        // 6.1勋章课兑换码
        // 6.1勋章课兑换码
    },
    mounted() {
        this.initDateTimestamp();
        this.fetchData();
        this.fetchTeam();
        this.fetchPosition();
        if (this.isCompanyAccount()) {
            this.fetchAccountInfo();
            this.fetchApplicationData();
            this.fetchMedalCdkey();

            this.getMedalCdkey();
            this.getMedalUserCdkey();
            this.fetchMedalExchange();
        } else {
            this.fetchCompany();
        }
    },
};
</script>

<style lang="scss">
.achievement-list-page {
    .filter {
        .input-width {
            max-width: 200px;
        }
    }

    .input-width {
        max-width: 300px;
    }

    .logo {
        width: 60px;
        height: 60px;
    }
    .footer {
        height: 44px;
        background: #f7f7f7;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-left: 20px;
        padding-right: 20px;
    }
    .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;
    }
}
</style>
